package main

import (
	"github.com/gorilla/websocket"
	"time"
	"global/core"
	"github.com/lunny/log"
)

const disconnectTimeWait = 10 * time.Second

type Client struct {
	Route 				string
	Handler 			*Handler
	HI 					HandlerInterface
	Manager 			*Manager
	Conn  				*websocket.Conn

	// 最后接收到 ping 的时间
	LastPingPongTime 	time.Time

	timer 				*time.Timer

	exitSignal 			chan interface{}
}

func NewClient(
	url string,
	m *Manager,
	hi HandlerInterface,
	conn *websocket.Conn) *Client {
	client := &Client{
		Route: 			url,
		Manager: 		m,
		HI: 			hi,
		Conn: 			conn,
		exitSignal: 	make(chan interface{}),
	}
	client.afterFunc()
	return client
}

func (c *Client) Start(ctx *core.Context) {
	c.Handler = NewHandler(c, ctx, c.Conn)
	c.Handler.run(c.HI)
	go func() {
		for {
			select {
			case m := <-c.exitSignal:
				log.Infof("Receive exit signal")
				_, ok := m.(*websocket.Conn)
				if ok {
					c.Handler.Exit()
				}
				c.timer.Stop()
				c.Close()
				c.Manager.outSignal <- c.Conn
			}
		}
	}()
}

func (c *Client) afterFunc()  {
	c.timer = time.AfterFunc(disconnectTimeWait, func() {
		c.exitSignal <- c.Conn
	})
}

func (c *Client) Reset() {
	c.timer.Reset(disconnectTimeWait)
}

func (c *Client) Close()  {
	if c.Conn != nil {
		c.Conn.Close()
	}
}

func (c *Client) ReadJson(m interface{}) error {
	return c.Conn.ReadJSON(m)
}

func (c *Client) WriteJson(m interface{}) error {
	err := c.Conn.WriteJSON(m)
	return err
}
